import random
from subprocess import Popen
from urllib import parse

import execjs
import requests
Popen.__init__.__kwdefaults__['encoding'] = "utf-8"

class BossCookieSpider:

    def __init__(self):
        self.core = """
    window = {
    document: {
        cookie: "",
        createElement: function(tag) {
            if (tag == "canvas") {
                return canvas
            } else if (tag == "caption") {
                return {
                    tagName: "CAPTION"
                }
            }
            
        },
        getElementById: function() {
            return false
        },
        title: ""
    },
    moveBy: function () {},
    moveTo: function () {},
    open: function(){},
    dispatchEvent: function(){return true},
    screen: {
        availHeight: 824,
        availWidth: 1536
    },
    navigator: {
        cookieEnabled: true,
        language: "zh-CN",
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36",
        appVersion: "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
    },
    decodeURI: global.decodeURI,
    location: {
        hostname: "www.zhipin.com",
        href: "https://www.zhipin.com/"
    },
    OfflineAudioContext: function () {
        this.createOscillator = function() {
            return {
                frequency: {
                    setValueAtTime: function() {}
                },
                connect: function (){},
                start: function (){},
            }
        },
        this.createDynamicsCompressor = function() {
            return {
                threshold: {
                    setValueAtTime: function () {},
                },
                setValueAtTime: function () {},
                knee: {
                    setValueAtTime: function () {},
                },
                ratio: {
                    setValueAtTime: function () {},
                },
                reduction: {
                    setValueAtTime: function () {},
                },
                attack: {
                    setValueAtTime: function () {},
                },
                release: {
                    setValueAtTime: function () {},
                },
                connect: function (){},
            }
        },
        this.startRendering = function (){}
    },
    eval: global.eval,
    history: {length: 1},
    outerHeight: 824,
    innerHeight: 150,
    outerWidth: 1536,
    innerWidth: 0,
    Math: global.Math,
    Date: global.Date,
}
window.open.toString = function (){return "function open() { [native code] }"}
document = window.document
navigator = window.navigator
screen = window.screen
canvas = {
    getContext: function getContext() {
        return CanvasRenderingContext2D
    },
    toDataURL: function toDataURL() {
        // 实际为canvas画布填充了“"k54kk5cA4*"”字样后，转成的图片链接
        return ""
    },
}
CanvasRenderingContext2D = {
    fillRect: function () {},
    fillText: function () {}
}
localStorage = {
    removeItem: function (key) {
        delete this[key]
    },
    getItem: function (key) {
        return this[key] ? this[key]: null;
    },
    setItem: function (key, value) {
        this[key] = "" + value;
    },
};
sessionStorage = {}
setInterval = window.setInterval = function (){}
setInterval.toString = function(){return "function setInterval() { [native code] }"}
setTimeout = function (){}
top = window.top = window
global = undefined;
child_process = undefined;
closed = {
    __proto__: ( 1>>3 >4 )["__proto__"]
}
function get_cookie(seed, ts, code) {
    var Buffer;
    process = undefined;
    function CustomEvent() {}
    eval(code);
    cookie = encodeURIComponent(new ABC().z(seed, parseInt(ts)+(480+new Date().getTimezoneOffset())*60*1000))
    console.log({cookie, cookie})
    return {cookie, cookie};
}
function encryption(seed, ts) {
    var code = new ABC().z(seed, parseInt(ts) + (480 + new Date().getTimezoneOffset()) * 60 * 1000);
    return encodeURIComponent(code)
}
        """

    def main(self):
        headers = {
            "user-agent": f"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/{random.randint(1, 999)}.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
        }
        url = f"https://www.zhipin.com/job_detail/"
        response = requests.get(url, headers=headers, )
        self.cookies_generate(response)

    def cookies_generate(self, response):
        query_str = parse.urlparse(response.url).query
        query_dict = {i.split("=")[0]: i.split("=")[1] for i in query_str.split("&")}
        js_name = query_dict.get("name")
        js_url = f"https://www.zhipin.com/web/common/security-js/{js_name}.js"
        js_res = requests.get(js_url, )
        js_text = js_res.text
        js_text = js_text.replace("typeof process", "typeof child_process")
        seed = parse.unquote(query_dict.get("seed"))
        ts = query_dict.get("ts")
        new_js_text = self.core + js_text
        new_js = execjs.compile(new_js_text)
        code = new_js.call("encryption", seed, ts)
        headers = {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
            "cookie": f"__zp_stoken__={code};"
        }
        url = "https://www.zhipin.com/c101280600-p100120/"
        response = requests.get(url, headers=headers, )
        print(response.text)
        pass


if __name__ == '__main__':
    boss_zhipin_cookie = BossCookieSpider()
    boss_zhipin_cookie.main()
